<template>
  <div class="app-container">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              v-model="queryParams.keyword"
              placeholder="搜索标题/内容"
              clearable
              @keyup.enter.native="handleQuery"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="handleQuery"
              />
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="queryParams.typeId"
              placeholder="选择题型"
              clearable
              @change="handleQuery"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="queryParams.difficult"
              placeholder="选择难度"
              clearable
              @change="handleQuery"
            >
              <el-option
                v-for="item in difficultyOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col :span="4" class="text-right">
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="handleAdd"
            >新增
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              :disabled="!hasSelection"
              @click="handleBatchDelete"
            >删除
            </el-button>
            <el-dropdown @command="handleExport" class="ml-10">
              <el-button type="success">
                导出<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="pdf">导出为PDF</el-dropdown-item>
                <el-dropdown-item command="word">导出为Word</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>
      </div>

      <!-- 全文搜索和相似题目搜索区域 -->
      <el-row :gutter="20" class="mb-20">
        <el-col :span="12">
          <el-card shadow="never" class="mb-20">
            <el-input
              v-model="fulltextKeyword"
              placeholder="全文搜索(标题和内容)"
              clearable
              @keyup.enter.native="handleFulltextSearch"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="handleFulltextSearch"
              />
            </el-input>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="never" class="mb-20">
            <el-popover
              placement="bottom"
              width="800"
              trigger="click"
              v-model="showSimilarSearchEditor"
            >
              <div style="margin-bottom: 10px;">
                <wang-editor v-model="similarSearchContent" mode="simple" />
              </div>
              <div style="text-align: right; margin: 0">
                <el-input-number
                  v-model="similarityThreshold"
                  :min="0.1"
                  :max="1"
                  :step="0.1"
                  size="small"
                  style="width: 120px; margin-right: 10px;"
                  placeholder="相似度阈值"
                ></el-input-number>
                <el-button size="mini" type="text" @click="showSimilarSearchEditor = false">取消</el-button>
                <el-button type="primary" size="mini" @click="handleSimilarSearchByText">搜索</el-button>
              </div>
              <el-button slot="reference" type="info" icon="el-icon-connection" style="width: 100%">
                根据题目文本查找相似题目
              </el-button>
            </el-popover>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分类树和内容区域 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="never">
            <div slot="header" class="clearfix">
              <span>分类筛选</span>
              <el-button
                style="float: right; padding: 3px 0"
                type="text"
                @click="resetCategory"
              >重置
              </el-button>
            </div>
            <el-input
              v-model="categoryFilterText"
              placeholder="输入分类名称搜索"
              clearable
              prefix-icon="el-icon-search"
            />
            <el-tree
              ref="categoryTree"
              class="filter-tree"
              :data="categoryTree"
              :props="categoryProps"
              :filter-node-method="filterCategoryNode"
              node-key="id"
              highlight-current
              @node-click="handleCategoryNodeClick"
            />
          </el-card>
        </el-col>
        <el-col :span="18">
          <!-- 题目卡片列表 -->
          <div v-loading="loading">
            <el-alert
              v-if="isSimilarSearchMode"
              title="当前为相似题目搜索结果"
              type="info"
              :closable="true"
              @close="exitSimilarSearchMode"
              show-icon
              class="mb-20"
            >
              <el-button type="text" @click="exitSimilarSearchMode">返回正常列表</el-button>
            </el-alert>

            <el-row :gutter="20">
              <el-col
                v-for="item in questionList"
                :key="item.id"
                :span="24"
                class="mb-20"
              >
                <el-card class="question-card" shadow="hover">
                  <!-- 头部 -->
                  <div slot="header" class="clearfix header-area">
                    <el-checkbox
                      v-model="selectedQuestionIds"
                      :label="item.id"
                      @click.native.stop
                      class="question-checkbox"
                    ></el-checkbox>
                    <span
                      class="question-title"
                      @click.stop="toggleSelect(item.id)"
                      v-html="item.title"
                    />
                    <div style="float: right;">
                      <el-tag
                        v-if="item.type_name"
                        size="small"
                        style="margin-right: 5px;"
                      >{{ item.type_name }}
                      </el-tag>
                      <el-tag
                        v-if="item.similarity"
                        size="small"
                        type="success"
                      >相似度: {{ (item.similarity * 100).toFixed(1) }}%
                      </el-tag>
                    </div>
                  </div>

                  <!-- 内容区域 -->
                  <div class="content-container" @click.stop="handleDetail(item)">
<!--                    <div-->
<!--                      class="question-content"-->
<!--                      v-html="item.content"-->
<!--                      @click.stop="handleDetail(item)"-->
<!--                    ></div>-->
                    <formula-renderer
                      class="question-content"
                      :html="item.content"
                    />
                  </div>

                  <!-- 难度评分 -->
                  <div class="difficulty-row">
                    <el-rate
                      v-model="item.difficult"
                      disabled
                      :colors="['#99A9BF', '#F7BA2A', '#FF9900','#ff00bb', '#ff002f']"
                    />
                  </div>

                  <!-- 知识点标签区域 -->
                  <div class="tags-container">
                    <el-tag
                      v-for="cat in item.categories.split(',')"
                      :key="cat"
                      size="mini"
                      type="info"
                      class="tag-item"
                    >{{ cat }}
                    </el-tag>
                  </div>

                  <!-- 操作按钮 -->
                  <div class="action-buttons">
                    <el-button
                      type="text"
                      icon="el-icon-edit"
                      @click.stop="handleUpdate(item)"
                    >编辑
                    </el-button>
                    <el-button
                      type="text"
                      icon="el-icon-connection"
                      @click.stop="handleSimilarSearch(item)"
                    >相似题
                    </el-button>
                    <el-button
                      type="text"
                      icon="el-icon-delete"
                      style="color: #f56c6c"
                      @click.stop="handleSingleDelete(item)"
                    >删除
                    </el-button>
                  </div>
                </el-card>
              </el-col>
            </el-row>

            <!-- 分页 -->
            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 题目详情对话框 -->
    <el-dialog
      :title="detailTitle"
      :visible.sync="detailVisible"
      width="80%"
      top="5vh"
    >
      <question-detail :question="currentQuestion"/>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关闭</el-button>
        <el-button
          type="primary"
          @click="handleUpdate(currentQuestion)"
        >编辑
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listQuestion,
  fulltextSearch,
  deleteQuestion,
  listQuestionTypes,
  exportPdf,
  exportWord,
  getSimilarQuestionsById,
  getSimilarQuestionsByText,
  listQuestion2
} from '@/api/question2/question'
import {getCategoryTree} from '@/api/question2/category'
import QuestionDetail from './QuestionDetail'
import WangEditor from '@/components/WangEditor'
import FormulaRenderer from "@/components/FormulaRenderer/index.vue";

export default {
  name: 'QuestionList',
  components: {FormulaRenderer, QuestionDetail, WangEditor},
  dicts: ['bis_question_difficulty'],
  data() {
    return {
      // 相似搜索相关状态
      showSimilarSearchEditor: false,
      similarSearchContent: '',
      similarityThreshold: 0.7,
      isSimilarSearchMode: false,
      originalQueryParams: null,

      // 添加选中题目数组
      selectedQuestions: [],
      selectedQuestionIds: [], // 修改变量名更清晰
      // 删除加载状态
      deleteLoading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: undefined,
        typeId: undefined,
        difficult: undefined,
        categoryId: undefined
      },
      fulltextKeyword: undefined,
      // 题目列表
      questionList: [],
      total: 0,
      loading: true,
      // 分类树
      categoryTree: [],
      categoryProps: {
        label: 'name',
        children: 'children'
      },
      categoryFilterText: '',
      // 题型选项
      typeOptions: [],
      // 难度选项
      difficultyOptions: [
        {value: 1, label: '简单'},
        {value: 2, label: '偏易'},
        {value: 3, label: '中等'},
        {value: 4, label: '偏难'},
        {value: 5, label: '困难'}
      ],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 详情对话框
      detailVisible: false,
      currentQuestion: null,
      detailTitle: ''
    }
  },
  created() {
    this.getList()
    this.getCategoryTree()
    this.getTypeOptions()
  },
  computed: {
    // 添加计算属性监控选中状态
    hasSelection() {
      return this.selectedQuestions.length > 0
    }
  },
  watch: {
    categoryFilterText(val) {
      this.$refs.categoryTree.filter(val)
    }
  },
  methods: {
    // 根据题目ID查找相似题目
    handleSimilarSearch(row) {
      this.loading = true
      getSimilarQuestionsById(row.id, {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      }, this.similarityThreshold).then(response => {
        console.log('response', response)
        this.isSimilarSearchMode = true
        this.originalQueryParams = {...this.queryParams}
        this.questionList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    // 根据题目文本查找相似题目
    handleSimilarSearchByText() {
      if (!this.similarSearchContent) {
        this.$message.warning('请输入题目内容')
        return
      }

      this.loading = true
      this.showSimilarSearchEditor = false

      getSimilarQuestionsByText(this.similarSearchContent, {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      }, this.similarityThreshold).then(response => {
        this.isSimilarSearchMode = true
        this.originalQueryParams = {...this.queryParams}
        this.questionList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    // 退出相似题目搜索模式
    exitSimilarSearchMode() {
      this.isSimilarSearchMode = false
      this.queryParams = {...this.originalQueryParams}
      this.getList()
    },

    // 处理导出
    handleExport(command) {
      if (this.selectedQuestionIds.length === 0) {
        this.$confirm('当前没有选中题目，是否导出所有查询结果?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.doExport(command, null);
        });
      } else {
        this.doExport(command, this.selectedQuestionIds);
      }
    },

    // 执行导出
    doExport(type, ids) {
      const query = {
        ...this.queryParams,
        questionIds: ids,
        includeAnswer: true,
        includeAnalysis: true
      };

      const loading = this.$loading({
        lock: true,
        text: '正在生成文件，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      try {
        const exportFn = type === 'pdf' ? exportPdf : exportWord;
        exportFn(query).then(response => {
          const blob = new Blob([response], {
            type: 'application/octet-stream'
          });
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = type === 'pdf'
            ? `题目列表_${new Date().toLocaleString()}.pdf`
            : `题目列表_${new Date().toLocaleString()}.docx`;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        }).finally(() => {
          loading.close();
        });
      } catch (error) {
        loading.close();
        this.$message.error('导出失败: ' + error.message);
      }
    },
    /** 查询题目列表 */
    getList() {
      this.loading = true
      listQuestion2(this.queryParams).then(response => {
        this.questionList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 全文搜索 */
    handleFulltextSearch() {
      if (!this.fulltextKeyword) {
        this.$message.warning('请输入搜索关键词')
        return
      }

      this.loading = true
      fulltextSearch({
        keyword: this.fulltextKeyword,
        categoryId: this.queryParams.categoryId,
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      }).then(response => {
        this.questionList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取分类树 */
    getCategoryTree() {
      getCategoryTree().then(response => {
        this.categoryTree = response.data
      })
    },
    // 获取题型选项
    getTypeOptions() {
      listQuestionTypes().then(response => {
        this.typeOptions = response.data.map(item => ({
          id: item.id,
          name: item.name,
          code: item.code,
          hasOption: item.hasOption,
          hasAnswer: item.hasAnswer,
          hasFile: item.hasFile,
          sort: item.sort
        }));

        // 如果是修改模式且有初始typeId，触发一次类型变更
        if (this.isEdit && this.form.typeId) {
          const type = this.typeOptions.find(t => t.id === this.form.typeId);
          if (type) {
            this.handleTypeChange(type);
          }
        }
      }).catch(error => {
        console.error('获取题型列表失败:', error);
        this.$message.error('获取题型列表失败');
      });
    },

    // 处理题型变化
    handleTypeChange(typeId) {
      const selectedType = this.typeOptions.find(item => item.id === typeId);
      if (!selectedType) return;

      // 根据题型特性动态调整表单
      this.showOptions = selectedType.hasOption > 0;
      this.showAnswers = selectedType.hasAnswer > 0;
      this.showAttachments = selectedType.hasFile > 0;

      // 初始化选项（如果是新增或切换题型）
      if (!this.isEdit) {
        this.initOptions(selectedType.hasOption);
        this.initAnswers(selectedType.hasAnswer);
      }
    },

    // 初始化选项
    initOptions(hasOption) {
      if (hasOption === 1 || hasOption === 2) {
        // 单选或多选题型，初始化两个默认选项
        this.form.options = [
          {optionCode: 'A', content: '', isCorrect: 0, sort: 1},
          {optionCode: 'B', content: '', isCorrect: 0, sort: 2}
        ];
      } else {
        this.form.options = [];
      }
    },

    // 初始化答案
    initAnswers(hasAnswer) {
      this.form.answers = hasAnswer === 1
        ? [{content: '', sort: 1}]
        : [];
    },
    /** 分类树筛选 */
    filterCategoryNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    /** 分类节点点击事件 */
    handleCategoryNodeClick(data) {
      if (data.isKnowledge === 1) return
      this.queryParams.categoryId = data.id
      this.handleQuery()
    },
    /** 重置分类筛选 */
    resetCategory() {
      this.queryParams.categoryId = undefined
      this.$refs.categoryTree.setCurrentKey(null)
      this.handleQuery()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 查看详情 */
    handleDetail(row) {
      this.currentQuestion = row
      this.detailTitle = '题目详情 - ' + row.id
      this.detailVisible = true
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push('/question2/input')
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push({
        path: '/question2/input',
        query: {id: row.id}
      })
    },
    // 切换选中状态
    toggleSelect(id) {
      const index = this.selectedQuestionIds.indexOf(id)
      if (index === -1) {
        this.selectedQuestionIds.push(id)
      } else {
        this.selectedQuestionIds.splice(index, 1)
      }
    },

    // 单独处理单个删除
    handleSingleDelete(row) {
      this.$confirm('确定要删除这道题目吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return deleteQuestion([row.id])
      }).then(() => {
        this.$message.success('删除成功')
        // 从选中数组中移除
        this.selectedQuestionIds = this.selectedQuestionIds.filter(id => id !== row.id)
        this.getList()
      })
    },
    // 批量删除
    handleBatchDelete() {
      if (this.selectedQuestionIds.length === 0) {
        this.$message.warning('请至少选择一道题目')
        return
      }

      this.$confirm(`确定要删除选中的${this.selectedQuestionIds.length}道题目吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return deleteQuestion(this.selectedQuestionIds)
      }).then(() => {
        this.$message.success('删除成功')
        this.selectedQuestionIds = []
        this.getList()
      })
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    }
  }
}
</script>

<style lang="scss" scoped>
.question-card {
  position: relative;
  min-height: 200px; /* 最小高度 */
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;

  /* 头部样式保持不变 */
  .header-area {
    display: flex;
    align-items: center;
    padding-right: 40px;
    flex-shrink: 0;
  }

  /* 内容区域 */
  .content-container {
    flex: 1;
    min-height: 60px; /* 最小内容高度 */
    margin: 10px 0;

    .question-content {
      max-height: 4.5em; /* 3行高度 (1.5em行高) */
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 3; /* 限制3行 */
      -webkit-box-orient: vertical;
      line-height: 1.5em;
      cursor: pointer;

      &:hover {
        overflow-y: auto;
        -webkit-line-clamp: unset;
      }

      /* 滚动条样式 */
      &::-webkit-scrollbar {
        width: 4px;
      }

      &::-webkit-scrollbar-thumb {
        background-color: #c1c1c1;
        border-radius: 2px;
      }
    }
  }

  /* 难度评分 */
  .difficulty-row {
    flex-shrink: 0;
    margin: 8px 0;
  }

  /* 知识点标签区域 */
  .tags-container {
    flex-shrink: 0;
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
    margin-bottom: 10px;

    .tag-item {
      margin: 0 !important;
    }
  }

  /* 操作按钮 */
  .action-buttons {
    flex-shrink: 0;
    text-align: right;
    margin-top: auto; /* 确保始终在底部 */
    padding-top: 10px;
    border-top: 1px solid #ebeef5;

    .el-button {
      padding: 0 8px;
    }
  }
}

/* 其他样式保持不变 */
.question-title {
  flex: 1;
  margin-left: 8px;
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.question-checkbox {
  ::v-deep .el-checkbox__label {
    display: none;
  }

  margin-right: 0;
}

/* 调整标签和按钮间距 */
.el-tag + .el-tag {
  margin-left: 5px;
}

.el-button + .el-button {
  margin-left: 5px;
}


.filter-tree {
  margin-top: 10px;
  height: calc(100vh - 320px);
  overflow-y: auto;
}

.mb-20 {
  margin-bottom: 20px;
}

.mr-5 {
  margin-right: 5px;
}

.mr-10 {
  margin-right: 10px;
}

.text-right {
  text-align: right;
}
</style>
